package com.audi.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.BaseActivity;
import com.audi.adapter.SQLiteAsusNewHelper;
import com.audi.adapter.SmartTriggerAdapter;
import com.audi.adapter.SmartTriggerNewAdapter;
import com.audi.dto.DescriptionSmartTrigger;
import com.audi.dto.DeviceItem;
import com.audi.dto.PlaceItem;
import com.audi.dto.SmartTriggerItem;
import com.audi.dto.SmartTriggerWhenItem;
import com.audi.dto.SmartTriggerWhenTriggerItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.view.BaseDeviceDialog;
import com.audi.view.DeviceUpdatePhoto;

public class DeviceDetailActivity extends BaseActivity implements ActionMessage {
	private ImageButton mImgBack, mImgDelete, mImgEditDevice;
	private TextView mTxtDeviceNameAction, mTxtDeviceName;
	private TextView mTxtLocation, mTxtPrivacy, mTxtTimeAdded;
	private TextView mBtnAction, mBtnInfomation;
	private LinearLayout mLnlAction, mLnlInfomation, mlnActionNull;


	private RelativeLayout locationDevice;
	private SmartTriggerAdapter mSmartTriggerAdapter;
	private ArrayList<SmartTriggerItem> mListTriggerArr;
	ListView listTrigger;
	private DeviceItem deviceItem = new DeviceItem();
	private ImageButton imageDevice;
	private DeviceUpdatePhoto mDeviceUpdatePhotoDeviceDetail;
	private SendMessage sendMessage = new SendMessage();
	// funtion edit name 0, location 1
	private int typeFuntion = 0;
	Activity activity;
	private BaseDeviceDialog updateDeviceDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_detail);
		initActionBar(R.layout.action_bar_device_detail);
		activity=this;
		deviceItem = (DeviceItem) getIntent().getExtras().getSerializable(
				"item");
		updateDeviceDialog = new BaseDeviceDialog(this);
		setDisableDrawer();
		getWidget();
		initData();
		addEventForWidget();
		mDeviceUpdatePhotoDeviceDetail = new DeviceUpdatePhoto(this);
		
	}

	private void getWidget() {
		mlnActionNull = (LinearLayout) findViewById(R.id.list_action_null);
		mlnActionNull.setVisibility(View.GONE);
		listTrigger = (ListView) findViewById(R.id.lst_action_device);
		mBtnAction = (TextView) findViewById(R.id.btn_home_action);
		mBtnInfomation = (TextView) findViewById(R.id.btn_infomation);
		mImgBack = (ImageButton) findViewById(R.id.img_back);
		mImgDelete = (ImageButton) findViewById(R.id.img_delete);
		mImgEditDevice = (ImageButton) findViewById(R.id.img_edit_device);
		mTxtDeviceNameAction = (TextView) findViewById(R.id.txt_device_name_action_bar);
		mTxtDeviceName = (TextView) findViewById(R.id.txt_device_name);
		mTxtLocation = (TextView) findViewById(R.id.txt_location);
		mTxtPrivacy = (TextView) findViewById(R.id.txt_privacy);
		mTxtTimeAdded = (TextView) findViewById(R.id.txt_time_added);
		mLnlAction = (LinearLayout) findViewById(R.id.linear_layout_home_action);
		mLnlInfomation = (LinearLayout) findViewById(R.id.linear_layout_infomation);		
		locationDevice = (RelativeLayout) findViewById(R.id.ll_location);
		imageDevice = (ImageButton) findViewById(R.id.img_device_type);

		dumpDataAction();
	}

	private void addEventForWidget() {
		mBtnInfomation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mLnlInfomation.setVisibility(View.VISIBLE);
				mBtnAction.setTextColor(Color.BLACK);
				mBtnInfomation.setTextColor(Color.WHITE);
				mBtnAction.setBackgroundResource(R.drawable.btn_tab_off_new);
				mBtnInfomation.setBackgroundResource(R.drawable.btn_tab_on_new);
				mImgDelete.setVisibility(View.VISIBLE);
			}
		});

		mBtnAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLnlAction.setVisibility(View.VISIBLE);
				mLnlInfomation.setVisibility(View.GONE);
				mImgDelete.setVisibility(View.GONE);
				mBtnAction.setTextColor(Color.WHITE);
				mBtnInfomation.setTextColor(Color.BLACK);
				mBtnAction.setBackgroundResource(R.drawable.btn_tab_on_new);
				mBtnInfomation.setBackgroundResource(R.drawable.btn_tab_off_new);
				//SendMessage sendMessage=new SendMessage();
				sendMessage.sendData(3013,null, handler2);
			
			}
		});
		locationDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				typeFuntion = 3;
				updateDeviceDialog.showSelectPlaceDialog(deviceItem,
						handlerUpdateDevice);
				Toast.makeText(DeviceDetailActivity.this,
						"Change location Device", Toast.LENGTH_SHORT).show();
			}
		});

		mImgBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		mTxtDeviceNameAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		mImgDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				typeFuntion = 1;
				removeDevice(handlerUpdateDevice);
			}
		});

		mImgEditDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				typeFuntion = 0;
				editNameDevice(handlerUpdateDevice);
			}
		});
		imageDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDeviceUpdatePhotoDeviceDetail.updatePhoto();
			}
		});

	}

	@SuppressLint("SimpleDateFormat")
	private void initData() {
		try {

			mTxtDeviceName.setText(deviceItem.getDeviceName());
			mTxtDeviceNameAction.setText(deviceItem.getDeviceName());
			mTxtLocation.setText(deviceItem.getDevicePlace());
			mTxtPrivacy.setText(getResources().getStringArray(
					R.array.list_privacy_text)[deviceItem.getCapability() - 1]);
			long millisecond = System.currentTimeMillis();
			Date date = new Date(millisecond);
			DateFormat df = new SimpleDateFormat("dd, MMM. yyyy");
			String dateString = df.format(date);
			mTxtTimeAdded.setText(dateString);
			mListTriggerArr = new ArrayList<SmartTriggerItem>();
			Log.d("=============", mListTriggerArr + "<<<");
			mSmartTriggerAdapter = new SmartTriggerAdapter(activity,
					mListTriggerArr);
			listTrigger.setAdapter(mSmartTriggerAdapter);
			// itemPlaceDetail= mSqlite.getInfoOfPlace(itemDeviceDetail
			// .getDevicePlaceId());
		} catch (Exception e) {
			Log.e("deviceDetail", e.toString());
		}
	}

	private void dumpDataAction() {
		
	}

	@Override
	public void onRefreshData() {
		// TODO Auto-generated method stub

	}

	int tempActionResult;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent myIntent = new Intent(this, ActivityReviewImageCrop.class);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 555) {
			mDeviceUpdatePhotoDeviceDetail.dimissUpdate();
			Log.d("start crop", "dgfgfdgfdgdf");
			tempActionResult = 0;
		}
		if (resultCode == RESULT_OK) {
			// user is returning from capturing an image using the camera
			if (requestCode == mDeviceUpdatePhotoDeviceDetail.cameraCapture) {
				mDeviceUpdatePhotoDeviceDetail
						.performcrop(mDeviceUpdatePhotoDeviceDetail.getPicUri());
				Log.d("start crop", "crop crop crop");
				tempActionResult = 1;
			} else if (requestCode == mDeviceUpdatePhotoDeviceDetail.picCrop) {
				myIntent.putExtra("Req",
						mDeviceUpdatePhotoDeviceDetail.getstatus());
				// myIntent.putExtra("activity",mActivity.getApplicationContext());
				this.startActivityForResult(myIntent, 555);

				Log.d("start crop", "reviview=====-''/////");
				tempActionResult = 0;
			}
			if (requestCode == mDeviceUpdatePhotoDeviceDetail.pickFromFile) {
				tempActionResult = 2;
				mDeviceUpdatePhotoDeviceDetail.setPicUri(data.getData());
				mDeviceUpdatePhotoDeviceDetail
						.performcrop(mDeviceUpdatePhotoDeviceDetail.getPicUri());
				Log.d("start crop", "pick  form file=====- " + tempActionResult);

			}
		} else {
			Log.d("close ", "======== close" + tempActionResult);
			// Toast.makeText(activity, "sssss", Toast.LENGTH_LONG).show();
			if (tempActionResult == 1) {
				mDeviceUpdatePhotoDeviceDetail.camphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
			}
			if (tempActionResult == 2) {
				// upPhoto.performcrop(upPhoto.getPicUri());
				mDeviceUpdatePhotoDeviceDetail.picphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
				// this.finish();
			}
		}
	}

	/**
	 * handlerUpdateDevice
	 * 
	 * @see call back update device
	 */
	private Handler handlerUpdateDevice = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_DEVICE)) > 0) {
								if (typeFuntion == 0) {
									Log.d("rename device", "OK!!!!");
									mTxtDeviceNameAction.setText(deviceItem
											.getDeviceName());
									mTxtDeviceName.setText(deviceItem
											.getDeviceName());
								} else if (typeFuntion == 1) {
									finish();
								} else if (typeFuntion == 3) {
									if (updateDeviceDialog.placeItem
											.getPlaceName() != null
											&& updateDeviceDialog.placeItem
													.getPlaceName().length() > 0) {
										mTxtLocation
												.setText(updateDeviceDialog.placeItem
														.getPlaceName());
										deviceItem
												.setDevicePlace(updateDeviceDialog.placeItem
														.getPlaceName());
									}
								}
							} else {
								if (typeFuntion == 0) {
									Toast.makeText(DeviceDetailActivity.this,
											"not rename device",
											Toast.LENGTH_LONG).show();
								} else if (typeFuntion == 1) {
									Toast.makeText(DeviceDetailActivity.this,
											"not delete device",
											Toast.LENGTH_LONG).show();
								} else if (typeFuntion == 3) {
									Toast.makeText(DeviceDetailActivity.this,
											"not change location of device",
											Toast.LENGTH_LONG).show();
								}
							}
						}
					} catch (Exception e) {
					}
				}
			});
		}
	};

	/**
	 * editNameDevice
	 * 
	 * @param Handler
	 *            callBack
	 * @see update name device
	 */
	public void editNameDevice(final Handler callBack) {

		final Dialog diaEditNameDialog;
		diaEditNameDialog = new Dialog(this);
		diaEditNameDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		diaEditNameDialog.setContentView(R.layout.rename_place_dialog);
		final EditText renameEditText = (EditText) diaEditNameDialog
				.findViewById(R.id.edt_rename_place_dilog_input);
		Button cancel = (Button) diaEditNameDialog
				.findViewById(R.id.btn_rename_place_dialog_skip);
		Button ok = (Button) diaEditNameDialog
				.findViewById(R.id.btn_rename_place_dialog_ok);
		renameEditText.setText(deviceItem.getDeviceName());
		renameEditText.setSelection(renameEditText.getText().length());
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				diaEditNameDialog.dismiss();
			}
		});

		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (renameEditText.getText().toString().length() > 0) {
					deviceItem.setDeviceName(renameEditText.getText()
							.toString());
					DeviceItem newItem = new DeviceItem();
					newItem.setDeviceId(deviceItem.getDeviceId());
					newItem.setDeviceName(deviceItem.getDeviceName());
					sendMessage.updateDevice(newItem, callBack);

				} else {
					Toast.makeText(DeviceDetailActivity.this,
							"Input name Device", Toast.LENGTH_LONG).show();
				}
				diaEditNameDialog.dismiss();
			}
		});

		diaEditNameDialog.show();
	}

	/**
	 * removeDevice
	 * 
	 * @param Handler
	 *            callBack
	 * @see remove device
	 */
	public void removeDevice(final Handler callBack) {

		final Dialog diaRemove;
		diaRemove = new Dialog(this);
		diaRemove.requestWindowFeature(Window.FEATURE_NO_TITLE);
		diaRemove.setContentView(R.layout.remove_card_dialog);
		TextView txtSure = (TextView) diaRemove
				.findViewById(R.id.txtRemoveDevcie);
		txtSure.setText(getString(R.string.remove_detail_device_dialog)
				+ deviceItem.getDeviceName() + " ?");
		Button cancel = (Button) diaRemove.findViewById(R.id.btn_remove_cancel);
		Button ok = (Button) diaRemove.findViewById(R.id.btn_remove_yes);
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				diaRemove.dismiss();
			}
		});
		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				DeviceItem newItem = new DeviceItem();
				newItem.setDeviceId(deviceItem.getDeviceId());
				newItem.setIsDeleted(1); // deleted=1 | undelete=0
				// sendMessage.updateDevice(newItem, callBack);
				sendMessage.sendData(UPDATE_DEVICE, newItem, callBack);
				diaRemove.dismiss();
			}
		});

		diaRemove.show();
	}
	Handler handler2 = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					Log.d("LOG=========", "===== get list TRIGGER");
					try {
						if (msg.arg1 != -1) {
							mListTriggerArr = new ArrayList<SmartTriggerItem>();
							ArrayList<SmartTriggerItem> result = (ArrayList<SmartTriggerItem>) msg
									.getData().getSerializable("3013");							
							mListTriggerArr=result;									
							mSmartTriggerAdapter = new SmartTriggerAdapter(activity, mListTriggerArr);
							listTrigger.setAdapter(mSmartTriggerAdapter);
							Log.d("LOG=========", "===============>>>>>>>");
							Log.d("LOG=========", "marboro=====" + mListTriggerArr.size());
							Log.d("LOG=========", "===============>>>>>>>");
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL]:" + e.toString());
					}
				}
			});
		}
	};
}
